<template>
  <div class="q-pa-md">    
    <t-data-grid ref="dataGrid1" 
        :rows="rows"
        :optColumns="optColumns" 
        :loading="loading" 
        :rowKey="rowKey"
        :pageIndex="pagination.page" 
        :pageSize="pagination.rowsPerPage"
        :rowsNumber="pagination.rowsNumber" 
        @request="onRequest" 
        :columnLinkFormat="columnLinkFormat">
    </t-data-grid>
  </div>
</template>

<script>
import options from './options';

import { onMounted, ref } from 'vue';
export default {
  setup() {
    const rows = ref([]);

    const pagination = ref({ page: 1, rowsPerPage: 3, rowsNumber: 2001, });

    const loading = ref(false);

    function onRequest(props) {
      debugger;
      const { page, rowsPerPage } = props.pagination;

      loading.value = true;

      setTimeout(() => {
        fetchFromServer(props.pagination);
      }, 1500);

    }

    function fetchFromServer(_pagination) {
      const { page, rowsPerPage, rowsNumber } = _pagination;
      const fetchCount = rowsPerPage === 0 ? rowsNumber : rowsPerPage;

      // calculate starting row of data
      const startRow = (page - 1) * rowsPerPage;

      fetch(
        `http://localhost:3004/users?_start=${startRow}&_limit=${fetchCount}`,
      ).then(response => {
        response.json().then(data => {
          rows.value.splice(0, rows.value.length, ...data);

          debugger;
          pagination.value.rowsNumber = 2001;
          pagination.value.page = page;
          pagination.value.rowsPerPage = rowsPerPage;

          loading.value = false;
        });
      });
    }
    let Widget = {};

    onMounted(() => {
      Widget.dataGrid1 = vm.dataGrid1.value;
      fetchFromServer(pagination.value, '');
    });

    let vm = {
      dataGrid1: ref(),

      rows,
      loading,
      columnLinkFormat: field => {
        debugger;
        console.log(field, Widget.dataGrid1.cellClickInfo.data[field]);
      },      
      pagination: pagination,
      rowKey: options.idField,
      optColumns: options.columns,
      onRequest,
    };
    return vm;
  },
};
</script>
